import { Injectable, NotFoundException } from '@nestjs/common';
import { CreateQuestionDto } from './dto/create-question.dto';
import { UpdateQuestionDto } from './dto/update-question.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Question } from './entities/question.entity';
import { Like, Repository, UpdateResult } from 'typeorm';
import { PaginationService } from 'src/common/service/pagination.service';
import { PaginationQueryDto } from 'src/common/dto/pagination-query.dto';
import { PaginationResult } from 'src/common/interfaces/pagination-results.interface';
import { QuestionQueryDto } from './dto/query-question.dto';
import { DelFlag } from 'src/common/enums/del-flag.enum';
import { Options } from 'src/common/interfaces/options.interface';

@Injectable()
export class QuestionService {
  constructor(
    @InjectRepository(Question)
    private questionRepository: Repository<Question>,
    private paginationService: PaginationService,
  ) { }

  async create(createQuestionDto: CreateQuestionDto): Promise<Question> {
    const question = this.questionRepository.create(createQuestionDto);
    return this.questionRepository.save(question);
  }

  async findAll(questionQueryDto: QuestionQueryDto): Promise<PaginationResult<Question>> {
    const { question, limit, page } = questionQueryDto;
    const where: any = {
      del_flag: DelFlag.ACTIVE
    };

    if (question) {
      where.question = Like(`%${question}%`);
    }

    return this.paginationService.paginate(this.questionRepository, { limit, where, page });
  }

  async findOne(id: string): Promise<Question> {
    const question = await this.questionRepository.findOne({ where: { id, del_flag: DelFlag.ACTIVE } });
    if (!question) {
      throw new NotFoundException(`Question with ID ${id} not found`);
    }
    return question;
  }

  async update(id: string, updateQuestionDto: UpdateQuestionDto): Promise<Question> {
    await this.questionRepository.update(id, updateQuestionDto);
    const updatedQuestion = await this.questionRepository.findOne({ where: { id, del_flag: DelFlag.ACTIVE } });
    if (!updatedQuestion) {
      throw new NotFoundException(`Question with ID ${id} not found`);
    }
    return updatedQuestion;
  }

  async remove(id: string): Promise<UpdateResult> {
    return await this.questionRepository.update(id, { del_flag: DelFlag.DELETED });
  }

  async delete(id: string): Promise<void> {
    await this.questionRepository.delete(id);
  }
   // 查询所有
   async findAllResultsOptions(): Promise<Options[]> {
    const questions = await this.questionRepository.find();
    return questions.map(question => ({ label: question.question, value: question.id }));
  }
}
